package com.teach;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

public class RandomAccessFileTest {

	public static void main(String[] args) throws Exception {
		
		/**
		 * in.txt
		 * ABC\r\nabc 65,66,67,13,10,97,98,99
		 */
		File file = new File("d:/upload/in.txt");
		RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
		int temp = randomAccessFile.read();
		System.out.println(temp);
//		System.out.println(randomAccessFile.readChar());//和writeChar一致
//		System.out.println(randomAccessFile.readUTF());//和writeUTF一致
		System.out.println(randomAccessFile.getFilePointer());
		byte[] bs = new byte[10];
		randomAccessFile.read(bs);
		System.out.println(Arrays.toString(bs));
		
		bs = new byte[10];
		randomAccessFile.seek(0);
		randomAccessFile.read(bs);
		System.out.println(Arrays.toString(bs));

		bs = new byte[10];
		randomAccessFile.seek(5);
		randomAccessFile.read(bs);
		System.out.println(Arrays.toString(bs));
		System.out.println(randomAccessFile.getFilePointer());
		System.out.println(randomAccessFile.length());
		
//		randomAccessFile.setLength(2048);//IOException 只读方式打开
		
		randomAccessFile = new RandomAccessFile(file, "rw");//以读写方式打开
		randomAccessFile.setLength(2048);
		randomAccessFile.setLength(2);

		randomAccessFile.write(71);//GB
		randomAccessFile.write(72);//GH
		bs = new byte[] {100,101,102,103};
		randomAccessFile.write(bs);//GHdefg
		randomAccessFile.seek(1);
		randomAccessFile.write(bs);//Gdefgg
		randomAccessFile.seek(10);
		randomAccessFile.write(bs);//Gdefgg    defg
		
		randomAccessFile.seek(14);
		System.out.println(randomAccessFile.getFilePointer());
		randomAccessFile.writeInt(99);
		System.out.println(randomAccessFile.getFilePointer());
		randomAccessFile.writeChar('A');
		System.out.println(randomAccessFile.getFilePointer());
		randomAccessFile.writeBoolean(true);
		System.out.println(randomAccessFile.getFilePointer());
		randomAccessFile.writeUTF("大家好！");
		System.out.println(randomAccessFile.getFilePointer());
		randomAccessFile.seek(14);
		System.out.println(randomAccessFile.readInt());
		randomAccessFile.seek(18);
		System.out.println(randomAccessFile.readChar());
		randomAccessFile.seek(20);
		System.out.println(randomAccessFile.readBoolean());
		randomAccessFile.seek(21);
		System.out.println(randomAccessFile.readUTF());
		randomAccessFile.close();
		
		
		
		
	}
}
